package com.shxy.rlzy.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 下载文件的工具类
 */
public class DownloadFileUtil {

    public static void downloadFile(String originalFileName, File file, HttpServletResponse response) {
        // 检查参数
        checkParam(originalFileName, file);

        response.reset();
        response.setContentLength((int) file.length());
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + originalFileName);

        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try{
            fileInputStream = new FileInputStream(file);
            byte[] buffers = new byte[1024];
            outputStream = response.getOutputStream();
            int length;
            while ((length = fileInputStream.read(buffers)) > 0) {
                outputStream.write(buffers, 0 ,length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 检查参数
     *
     * @param originalFileName
     * @param file
     */
    private static void checkParam(String originalFileName, File file) {
        if (StringUtils.isBlank(originalFileName)) {
            throw new RuntimeException("输入的原始文件名为空");
        }
        if (file == null || !file.exists()) {
            throw new RuntimeException("待下载的文件不存在");
        }
    }
}